<?php
/**
 * Created by PhpStorm.
 * 商家充值服务
 * User: caicm
 * Date: 2017/6/26
 * Time: 14:34
 */

namespace WMApi\Service;


use SDXApi\Model\PaymentModel;
use WMApi\Model\WmSellerAccountRecordModel;
use WMApi\Model\WmSellerModel;
use WMApi\Model\WmSellerRechargeLogModel;

class SellerRechargeService {

    /**
     * 充值业务处理（支付宝支付、京东支付）
     * Created By caicm
     * @param int $seller_id 商家id
     * @param int $pay_id 支付id
     * @param int $money_id 金额id
     * @param string $trade_type 支付类型。默认为空：为公众号支付，“app”:app支付
     * @return mixed
     */
    public function recharge_pay($seller_id=0, $pay_id=0, $money_id=0, $trade_type='app'){

        $pay_id = $this->get_pay_way($pay_id);              //支付方式
        $money = $this->get_recharge_money($money_id);      //充值金额
        $out_trade_no = get_recharge_sn();                  //充值单号

        $payment_model = new PaymentModel();
        $recharge_log_model = new WmSellerRechargeLogModel();

        //写入充值日志表
        $add_recharge_log = $recharge_log_model->add_recharge_log($seller_id, $money, $pay_id, $out_trade_no);
        if(!$add_recharge_log){
            returnApiError('操作失败！');
        }

        $subject = "充值，金额:".$money;                                         //订单名称，必填
        $return_host = $this->get_return_host($_SERVER['HTTP_HOST']);           //获取同步域名
        $return_url = "https://".$return_host."/?index=/mine";                  //同步判断地址
        $total_fee = $money;                                                    //付款金额，必填
        $body = "账户充值";                                                     //商品描述，可空

        switch ($pay_id){
            //支付宝
            case 2:
                $show_url = "https://".$return_host."/index.php";                               //收银台页面上，商品展示的超链接，必填
                $notify_url = "http://".$_SERVER['HTTP_HOST']."/alipay_wm_seller_recharge.php";    //异步判断支付结果
                if($trade_type=="app"){
                    $function_name = 'app_alipay';
                }else{
                    $function_name = 'alipay';
                }

                $payinfo = $payment_model->$function_name($out_trade_no, $subject, $total_fee, $show_url, $body, $notify_url, $return_url, 1, true);
                break;

            //京东支付
            case 7:
                $notify_url = "http://".$_SERVER['HTTP_HOST']."/jd_wm_seller_recharge.php";             //异步判断支付结果
                $return_url = "http://".$return_host."/?index=/paySus?money=".$money;                   //同步判断地址
                if($trade_type=="app"){
                    $function_name = 'app_jdpay';
                }else{
                    $function_name = 'jdpay';
                }

                $payinfo = $payment_model->$function_name($out_trade_no, $subject, $total_fee, $body, $notify_url, $return_url, 1, $seller_id, true);
                break;

            default:
                returnApiError('支付方式有误！');
                break;
        }

        return $payinfo;

    }

    /**
     * 充值回调处理业务
     * Created By caicm
     * @param int $pay_id 支付方式 1-微信支付 2-支付宝 7-京东支付
     * @param string $out_trade_no 充值单号
     * @param string $trade_no 交易流水号
     * @param int $total_fee 交易金额
     * @return bool
     */
    public function recharge_notifypay($pay_id=0, $out_trade_no='', $trade_no='', $total_fee=0){
        $recharge_log_model = new WmSellerRechargeLogModel();
        $record_model = new WmSellerAccountRecordModel();
        $seller_model = new WmSellerModel();
        $recharge_log_model->startTrans();

        $log_info = $recharge_log_model->find_log_info($pay_id, $out_trade_no);
        //已支付
        if($log_info['pay_state'] == 1){
            return true;
        }

        //支付金额与发起金额不等
        if($log_info['money'] != $total_fee){
            return false;
        }

        /**
         * 修改充值日志状态
         */
        $update_log_state = $recharge_log_model->update_log_state($log_info['id'], $trade_no);

        /**
         * 修改商家账户余额
         */
        $update_account_money = $seller_model->add_account_money($log_info['seller_id'], $log_info['money']);

        //商家账户余额
        $account_money = $seller_model->get_account_money($log_info['seller_id']);

        /**
         * 写入商家账户余额操作记录
         */
        $record_note = "账户充值：{$log_info['money']},充值单号：{$log_info['recharge_sn']}";
        $add_record_state = $record_model->add_record($log_info['seller_id'], 0, 4, $log_info['id'], 2, $log_info['money'], $record_note, $account_money);

        if($update_log_state && $update_account_money && $add_record_state){
            $recharge_log_model->commit();
            return true;
        }else{
            $recharge_log_model->rollback();
            return false;
        }

    }


    /**
     * 支付方式
     * Created By caicm
     * @param int $pay_id
     * @return bool
     */
    protected function get_pay_way($pay_id=0){
        $list = array();
        $pay_way = get_pay_way();
        foreach ($pay_way as $value){
            $list[$value['pay_id']] = $value;
        }
        if($list[$pay_id]){
            return $list[$pay_id]['pay_id'];
        }else{
            returnApiError('支付方式有误！');
        }
    }

    /**
     * 充值金额
     * Created By caicm
     * @param int $money_id
     * @return bool
     */
    protected function get_recharge_money($money_id=0){
        $list = array();
        $money_type = M('wm_seller_recharge_money_type')->field('money_id,money')->order('sort desc')->select();
        foreach ($money_type as $value){
            $list[$value['money_id']] = $value;
        }
        if($list[$money_id]){
            return $list[$money_id]['money'];
        }else{
            returnApiError('充值金额参数有误！');
        }
    }

    /**
     * 获取支付同步返回域名
     * @param $host
     * @return string
     */
    private function get_return_host($host){
        if($host=='api.shidexian.com'){
            $return_host = "w.shidexian.com";
        }elseif($host=='apitest.shidexian.com'){
            $return_host = "test.shidexian.com";
        }else{
            $return_host = "w.shidexian.com";
        }
        return $return_host;
    }



}